package xyz.xcvu.ma2.module;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import me.chanjar.weixin.cp.bean.message.WxCpXmlMessage;
import me.chanjar.weixin.cp.bean.message.WxCpXmlOutImageMessage;
import me.chanjar.weixin.cp.bean.message.WxCpXmlOutMessage;
import me.chanjar.weixin.cp.bean.message.WxCpXmlOutTextMessage;
import me.chanjar.weixin.cp.config.WxCpConfigStorage;
import me.chanjar.weixin.cp.config.impl.WxCpDefaultConfigImpl;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.core.annotation.MagicModule;
import org.ssssssss.script.annotation.Comment;
import xyz.xcvu.ma2.utils.JsonUtils;

import java.util.Map;

@Component
@MagicModule("cp")
public class Cp {

    @Comment("获取企业微信实例")
    public WxCpService getService(
            @Comment("企业ID") String corpId,
            @Comment("应用ID") Integer agentId,
            @Comment("应用密钥") String corpSecret,
            @Comment("应用Token") String token,
            @Comment("应用Key") String aesKey
    ){
        WxCpService wxService = new WxCpServiceImpl();
        WxCpDefaultConfigImpl configStorage = new WxCpDefaultConfigImpl();
        configStorage.setCorpId(corpId);
        configStorage.setAgentId(agentId);
        configStorage.setCorpSecret(corpSecret);
        configStorage.setToken(token);
        configStorage.setAesKey(aesKey);
        wxService.setWxCpConfigStorage(configStorage);
        return wxService;
    }

    @Comment("解密接收到的消息体")
    public WxCpXmlMessage getWxMessage(
            @Comment("加密的xml字符串") String xml,
            @Comment("企业微信实例") WxCpService wxService,
            @Comment("时间戳") String timestamp,
            @Comment("随机字符串") String nonce,
            @Comment("消息校验字符串") String msg_signature
    ) {
        WxCpConfigStorage wxCpConfig = wxService.getWxCpConfigStorage();
        return WxCpXmlMessage.fromEncryptedXml(xml, wxCpConfig, timestamp, nonce, msg_signature);
    }

    @Comment("构造文本消息")
    public WxCpXmlOutMessage textBuild(
            @Comment("文本内容") String content,
            @Comment("接收到的消息体") WxCpXmlMessage wxMessage) {
        WxCpXmlOutTextMessage m = WxCpXmlOutMessage.TEXT().content(content)
                .fromUser(wxMessage.getToUserName()).toUser(wxMessage.getFromUserName())
                .build();
        return m;
    }

    @Comment("构造图片消息")
    public WxCpXmlOutMessage imageBuild(
            @Comment("图片资源ID") String content,
            @Comment("接收到的消息体") WxCpXmlMessage wxMessage) {
        WxCpXmlOutImageMessage m = WxCpXmlOutMessage.IMAGE().mediaId(content)
                .fromUser(wxMessage.getToUserName()).toUser(wxMessage.getFromUserName())
                .build();
        return m;
    }
}
